package com.wangxiaotao.Controller;
import com.wangxiaotao.Pojo.Goods;
import com.wangxiaotao.Pojo.User;
import com.wangxiaotao.Pojo.Order;
import com.wangxiaotao.Service.AdminService;
import com.wangxiaotao.Service.LoginService;
import com.wangxiaotao.WebSocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

@Controller
public class LoginController {
    @Autowired
    LoginService loginService;
    @Autowired
    AdminService adminService;
    @RequestMapping(value = "login.do" ,method = RequestMethod.POST)
    public String login(String username, String password, HttpServletRequest request){
        List<User> userList=loginService.queryByusername(username);
        User user=null;
        try {
            user=userList.get(0);
        }
        catch (Exception e){
            request.setAttribute("MSG","登录失败，用户名不存在");
            return "login";
        }
        if(user.getPassword().equals(password)){
            request.getSession().setAttribute("user",user);
            int roleid=user.getRole_id();
            if(roleid==1){//商家操作 获取点餐数据
                List<Order>orderList=adminService.getoderlist();
                request.getSession().setAttribute("orderList",orderList);
                request.setAttribute("orderList",orderList);
                request.setAttribute("name",user.getName());
                return "admin";
            }
            else{//用户操作
                List<Goods>goodsList=adminService.getallgoods();
                request.getSession().setAttribute("goodsList",goodsList);
                request.setAttribute("goodsList",goodsList);
                request.setAttribute("name",user.getName());
                request.setAttribute("username",user.getUsername());
                return "food";
            }
        }
        else {
            request.setAttribute("MSG","登录失败，密码错误");
            return "login";
        }
    }
    @RequestMapping(value = "register.do",method = RequestMethod.POST)
    public void register(User user,HttpServletRequest request){
        if(loginService.queryByusername(user.getUsername()).size()!=0){
            request.setAttribute("MSG","用户名已被注册");
        }
        else{
            loginService.InsertUser(user);
            request.setAttribute( "MSG","注册成功");
        }
    }
    @RequestMapping(value = "exit.do",method = RequestMethod.POST)
    public void out(HttpServletRequest request){
        request.getSession().removeAttribute("user");//退出登录
    }
}
